import { FairyEditor, System } from 'csharp';
const App = FairyEditor.App;
//后缀数组
let suffixArray: string[] = ["Button","Com","ComboBox", "Decorate", "Extension","Font", "Label", "MovieClip","PopupMenu","ProgressBar","ScrollBar", "Slider","View","WindowFrame"]
let errorMsg1 = "首字母未大写,不符合驼峰命名法";
let errorMsg2 = "后缀命名不符合规范";

export default class Utils {

  /**
   * 查找组件命名是否规范
   */
  public static findAllPackagesComName(): void {

    let allPackages = App.project.allPackages;
    for (let index = 0; index < allPackages.Count; index++) {
      let pkg: FairyEditor.FPackage = allPackages.get_Item(index);
      console.log("开始检查" + pkg.name + "包文件命名规范");
      for (let j = 0; j < pkg.items.Count; j++) {

        let pkgItem = pkg.items.get_Item(j);
        // console.log("ptype:" + pkgItem.type);
        if (pkgItem.type == "component" || pkgItem.type == "font" || pkgItem.type == "movieclip") {

          let pkgName = pkgItem.name;
          //有下划线截取前半部分,然后再根据上面的
          if (Utils.ContainXiaHuaXian(pkgName)) {
            let firstPartString = pkgName.split("_")[0];
            // console.log("firstPartString:"+firstPartString);
            Utils.JudgeName(firstPartString, pkgItem);
          }
          else {
            Utils.JudgeName(pkgName, pkgItem);
          }
        }
      }
    }
  }

  /**
   * 驼峰命名法，后缀结尾是否在上面数组中
   * @param pkgName
   * @param pkgItem
   */
  private static JudgeName(pkgName: string, pkgItem: FairyEditor.FPackageItem) {
    if (!Utils.FisrtCharUp(pkgName)) {
      console.error(pkgItem.file + errorMsg1);
    }

    else {
      if (!Utils.ContainSuffixArray(pkgName)) {
        console.error(pkgItem.file + errorMsg2);
      }
    }
  }

  /**
   *
   * 组件后缀是否包含在上面后缀数组中
   *
   * @param pkgName
   * @returns
   */
  public static ContainSuffixArray(pkgName: string): boolean {

    let containSuffixArray: boolean = false;
    for (let k = 0; k < suffixArray.length; k++) {
      let suffix = suffixArray[k];
      // console.log("suffix:"+suffix);
      let reg = new RegExp(eval(`/.*(.{${suffix.length}})/`));
      if (pkgName.match(reg)) {
        let matchName = pkgName.match(reg)[1];
        if (matchName == suffix) {
          // console.log("matchName:"+matchName);
          containSuffixArray = true;
          break;
        }
      }
    }
    return containSuffixArray;
  }


  /**
   *  判断首字母是否大写
   * @param str
   * @returns
   */
  public static FisrtCharUp(str: string): boolean {
    let fisrtChar = str[0];
    let d = /^[A-Z][A-z0-9]*$/;
    return d.test(fisrtChar);

  }

  /**
   *
   * @param str 是否包含数字
   * @returns
   */
  public static ContainNum(str: string): boolean {
    let d = /\d/;
    return d.test(str);
  }

  /**
   *
   * @param str 是否包含下划线
   * @returns
   */
  public static ContainXiaHuaXian(str: string): boolean {
    let d = /\_+/g;
    return d.test(str);
  }
}